<template>
  <div>
    <div  class="barrages-drop">
      <video
        id="videoId"
        controls = "true"
        :height="boxHeight+350"
        :width="boxWidth">
      </video>
      <vue-baberrage
        :isShow="barrageIsShow"
        :barrageList="barrageList"
        :maxWordCount="maxWordCount"
        :throttleGap="throttleGap"
        :loop="barrageLoop"
        :boxHeight="boxHeight"
        :messageHeight="messageHeight"
        :boxWidth="boxWidth-300"
      >
      </vue-baberrage>
      <Card style="float: right;height: 500px;width: 500px;">
        <Scroll  height="450">
          <ul v-for="item in msgs">
            <li>{{item.chatAvatar}}　　　{{item.chatTime}}</li>
            <li>　　{{item.chatContent}}</li>
          </ul>
        </Scroll>
        <p  ><i-input v-model="sendmsg" placeholder="请输入..." style="width: 300px"></i-input>
          <i-button type="primary" @click="addToList(1)">发送消息</i-button></p>
      </Card>
    </div>

    <i-input v-model="sendmsg" placeholder="请输入..." style="width: 800px"></i-input>
    <i-button  type="primary" @click="addToList(2)">发送弹幕</i-button>

    <p>当前在线：{{onlineNumber}}</p>
    <div v-for="item in onlineUserList">
      <p>{{item}}</p>
    </div>
  </div>
</template>
<script>
    // import { onlineList } from '@/api/data'
    import { MESSAGE_TYPE } from 'vue-baberrage'
    import flvjs from 'flv.js'
    export default {
        name: 'level_2_1',
        data () {
            return {
                type:0,
                sendmsg: '土狗就是个辣鸡~',
                barrageIsShow: true,
                messageHeight: 3,
                boxHeight: 150,
                boxWidth:1000,
                barrageLoop: true,
                maxWordCount: 3,
                throttleGap: 5000,
                barrageList: [],
                t:'',
                userId:0,
                userName:'游客',
                msgs:[],
                currentId:1,
                msgHeadImageURL:'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3064584167,3502823640&fm=26&gp=0.jpg',
                sendTime:'',
                chatRoomWebsocket:'',
                onlineUserList:[],
                onlineNumber:0

            }
        },
        created() {
            this.userId=parseInt(Math.random()*1000000);
            this.userName=this.userName+this.userId;
            console.log(this.userName);
            this.t = window.setInterval(this.getChatUserList, 5000);
        },
        beforeDestroy() {
            clearInterval(this.t);
        },
        destroyed() {
            this.websocketClose();
        },
        mounted(){
            console.log(this.$route.query.id);
            if (flvjs.isSupported()){
                var videoElement = document.getElementById('videoId');
                var flvPlayer = flvjs.createPlayer({
                    type: 'flv',
                    "isLive": true,
                    url: 'http://localhost:7001/stream/'+this.$route.query.id+'.flv'
                });
                flvPlayer.attachMediaElement(videoElement);
                flvPlayer.load();
                // flvPlayer.play();
            }
        },
        methods: {
            initWebSocket() {
                if (typeof WebSocket != "undefined") {
                    this.supported = "支持 websocket";
                } else {
                    this.supported = "不支持 websocket";
                }
                //ws地址
                const wsuri = "ws://localhost:8888/websocket/" + this.$route.query.id + "/" + this.type + "/" + this.userId;
                this.chatRoomWebsocket = new WebSocket(wsuri);
                this.chatRoomWebsocket.onerror = this.websocketOnError;
                this.chatRoomWebsocket.onmessage = this.websocketOnMessage;
                this.chatRoomWebsocket.onclose = this.websocketOnClose;
            },
            //连接发生错误的回调方法
            websocketOnError() {
                console.log("WebSocket 连接发生错误");
            },
            //接收到消息的回调方法
            websocketOnMessage(event) {
                console.log(event);
                let data = JSON.parse(event.data);
                // this.msgHeadImageURL = data.chatImage ? data.chatImage : userPhoto;
                if (data.chatUser != this.userId&&data.chatType=='1') {
                    this.msgs.push(data);
                }
                if (data.chatUser != this.userId&&data.chatType=='2') {
                    this.barrageList.push({
                        id: ++this.currentId,
                        avatar: this.msgHeadImageURL,
                        msg: data.chatContent,
                        barrageStyle: "normal",
                        time: 5,
                        type: MESSAGE_TYPE.NORMAL,
                        position: "bottom"
                    });
                }
            },
            //连接关闭的回调方法
            websocketOnClose(e) {
                console.log("WebSocket 连接关闭", e);
            },
            //关闭 WebSocket 连接
            websocketClose() {
                this.chatRoomWebsocket.close();
            },
            addToList(type) {
                if (this.sendmsg.split(" ").join("").length != 0) {
                    //获取当前时间
                    var time = new Date();
                    this.sendTime =
                        time.getHours() +
                        ":" +
                        (time.getMinutes() < 10
                            ? "0" + time.getMinutes()
                            : time.getMinutes());
                    let messageData = {
                        chatContent: type==2?this.userName+":"+this.sendmsg:this.sendmsg,
                        chatUser: this.userId,
                        chatAvatar: this.userName,
                        chatImage: this.msgHeadImageURL,
                        chatTime: this.sendTime,
                        chatType:type
                    };
                    if (this.chatRoomWebsocket.readyState != "1") {
                        // 如果按下按钮时不是连接状态，重连并等到连接成功再发送消息
                        this.initWebSocket();
                        this.chatRoomWebsocket.onopen = () => {
                            this.chatRoomWebsocket.send(JSON.stringify(messageData));
                            //发送消息
                            if (type==1) {
                                this.msgs.push({
                                    chatContent: this.sendmsg,
                                    chatUser: this.userId,
                                    chatAvatar: this.userName,
                                    chatImage: this.msgHeadImageURL,
                                    chatTime: this.sendTime,
                                });
                            }else{
                                this.barrageList.push({
                                    id: ++this.currentId,
                                    avatar: this.msgHeadImageURL,
                                    msg: messageData.chatContent,
                                    barrageStyle: "normal",
                                    time: 5,
                                    type: MESSAGE_TYPE.NORMAL,
                                    position: "bottom"
                                });
                            }
                            this.sendmsg = "";
                        };
                    } else {
                        this.chatRoomWebsocket.send(JSON.stringify(messageData));
                        //发送消息
                        if (type==1) {
                            this.msgs.push({
                                chatContent: this.sendmsg,
                                chatUser: this.userId,
                                chatAvatar: this.userName,
                                chatImage: this.msgHeadImageURL,
                                chatTime: this.sendTime,
                            });
                        }else{
                            this.barrageList.push({
                                id: ++this.currentId,
                                avatar: this.msgHeadImageURL,
                                msg: messageData.chatContent,
                                barrageStyle: "normal",
                                time: 5,
                                type: MESSAGE_TYPE.NORMAL,
                                position: "bottom"
                            });
                        }
                        this.sendmsg = "";
                    }
                }
                // list.forEach((v) => {
                //  this.barrageList.push({
                //    id: v.id,
                //    avatar: v.avatar,
                //    msg: v.msg,
                //    time: v.time,
                //    type: MESSAGE_TYPE.NORMAL,
                //    barrageStyle: v.barrageStyle
                //  });
                // });
            },
            getChatUserList() {
                let data = {
                    sid: this.$route.query.id,
                    type: 1
                };
                // onlineList(data).then(res => {
                //     // console.log(res);
                //     // if (res.data.state == 200) {
                //     this.onlineNumber = res.data.count;
                //     this.onlineUserList = res.data.userList;
                //     console.log(this.onlineNumber);
                //     console.log(this.onlineUserList);
                //     // }
                // });
            },

        }

    }
</script>
<style  lang="less">
  .barrages-drop {
  .blue {
    border-radius: 100px;
    background: #e6ff75;
    color: #fff;
  }

  .green {
    border-radius: 100px;
    background: #75ffcd;
    color: #fff;
  }
  .red {
    border-radius: 100px;
    background: #e68fba;
    color: #fff;
  }
  .yellow {
    border-radius: 100px;
    background: #dfc795;
    color: #fff;
  }
  .baberrage-stage {
    position: absolute;
    width: 100%;
    height: 212px;
    overflow: hidden;
    top: 0;
    margin-top: 130px;
  }
  }
</style>
